package com.sunxd.rule.judge.handler;


import com.google.common.collect.Maps;
import com.sunxd.rule.judge.ConditionJudge;
import com.sunxd.rule.judge.beans.param.Condition;
import com.sunxd.rule.judge.support.DefaultConditionSupportJudge;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;

/**
 * @author sun.xd
 * @description: description
 * @date 2022/2/10 17:46
 */
@Component
public abstract class AbsConditionHandler implements ApplicationContextAware {

    public ConditionJudge conditionJudge;

    private static final Map<String, AbsConditionHandler> conditionHandlerMap = Maps.newHashMap();

    protected AbsConditionHandler() {
        register(operatorType(), this);
    }


    /**
     * 注册
     *
     * @param operatorType        操作类型
     * @param absConditionHandler 条件处理器
     */
    public void register(String operatorType, AbsConditionHandler absConditionHandler) {
        conditionHandlerMap.put(operatorType, absConditionHandler);
    }

    public abstract String operatorType();

    /**
     * 比较表达式
     *
     * @param condition condition
     * @return Boolean
     */
    public abstract Boolean doJudge(Condition condition);

    public static AbsConditionHandler getHandler(String operatorType) {
        AbsConditionHandler absConditionHandler = conditionHandlerMap.get(operatorType);
        if (Objects.isNull(absConditionHandler)) {
            return null;
        }
        return absConditionHandler;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.conditionJudge = applicationContext.getBean(DefaultConditionSupportJudge.class);
    }


}
